<?php

namespace App\Http\Controllers;

use App\Model\Account;
use App\Model\User;
use Illuminate\Http\Request;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;

class AuthController extends ApiController
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
//        $this->middleware('jwt.auth', ['except' => ['login','miniProgramLogin']]);
//        $this->middleware('auth:api', ['except' => ['login']]);
//        $this->middleware('myauth', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['name', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $this->setHeader(['Authorization'=>'Bearer '.$token]);
        return $this->message('登录成功！');

        return $this->respondWithToken($token);
    }


    public function hlogin(Request $request){
        $param = $request->only(['name','password']);
        $where = [
            'LoginUser'=>$param['name'],
//            'LoginPass'=>base64_encode($param['password']),
        ];
        $user = Account::query()->select(['EmpID','LoginUser','LoginPass'])->where($where)->first();
        $originPass = preg_replace('/[\x00-\x1F\x7F]/u', '', base64_decode($user['LoginPass']));
        if($user and $originPass == $param['password']){
            $token = auth()->login($user);
            $this->setHeader(['Authorization'=>'Bearer '.$token]);
            return $this->message('登录成功！');
        }else{
            return $this->failed('账号不存在或密码错误！',FoundationResponse::HTTP_UNAUTHORIZED);
        }


    }

    public function miniProgramLogin(Request $request){
        $param = $request->only(['code','type']);
        switch ($param['type']){
            case 'weixin':
                $miniProgram = EasyWeChat::miniProgram();
                $wxSession = $miniProgram->auth->session($param['code']);
                if(isset($wxSession['openid'])){
                    $user = User::query()->where(['wechat_openid'=>$wxSession['openid']])->first();
                    if($user){
                        $token = auth()->login($user);
                        $this->setHeader(['Authorization'=>'Bearer '.$token]);
                        return $this->message('登录成功！');
                    }else{
                        $createUser = User::query()->create(['wechat_openid'=>$wxSession['openid']]);
                        $token = auth()->login($createUser);

                        $this->setHeader(['Authorization'=>'Bearer '.$token]);
                        return $this->message('首次登录成功！');

                        return $this->failed('账号未绑定，请先绑定或注册',FoundationResponse::HTTP_UNAUTHORIZED);
                    }
                }else{
                    return $this->failed('获取微信授权失败！');
                }
                return $this->success($wxSession);
                break;
            default:
                return $this->failed('暂时不支持其他小程序登录');
        }
    }

    /**
     * 绑定已有账号
     * @param Request $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * author: jht
     */
    public function binding(Request $request){
        $credentials = request(['name', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return $this->failed('身份验证失败',FoundationResponse::HTTP_UNAUTHORIZED);
        }

        $param = $request->only(['code','type']);
        switch ($param['type']){
            case 'weixin':
                $miniProgram = EasyWeChat::miniProgram();
                $wxSession = $miniProgram->auth->session($param['code']);
                if(isset($wxSession['openid'])){
                    $user = User::query()->where(['wechat_openid'=>$wxSession['openid']])->first();
                    if($user){
                        return $this->failed('此微信已绑定过账号，不能重复绑定',FoundationResponse::HTTP_UNAUTHORIZED);
                    }else{
                        $id = auth()->id();
                        $result = User::query()->find($id)->update(['wechat_openid'=>$wxSession['openid']]);
                        $this->setHeader(['Authorization'=>'Bearer '.$token]);
                        return $this->message('绑定成功');
                    }
                }else{
                    return $this->failed('获取微信授权失败！');
                }
                break;
            default:
                return $this->failed('暂时不支持其他小程序登录');
        }
    }


    public function regist(Request $request){
        $credentials = request(['name', 'password']);

        $user = User::query()->where(['name'=>$credentials['name']])->first();
        if($user){
            return $this->failed('用户已存在！');
        }

        $param = $request->only(['code','type']);
        switch ($param['type']){
            case 'weixin':
                $miniProgram = EasyWeChat::miniProgram();
                $wxSession = $miniProgram->auth->session($param['code']);
                if(isset($wxSession['openid'])){
                    $user = User::query()->where(['wechat_openid'=>$wxSession['openid']])->first();
                    if($user){
                        return $this->failed('此微信已绑定过账号，请直接登录',FoundationResponse::HTTP_UNAUTHORIZED);
                    }else{
                        $credentials['wechat_openid'] = $wxSession['openid'];
                    }
                }else{
                    return $this->failed('获取微信授权失败！');
                }
                break;
            default:
                break;
        }

        $createUser = User::query()->create($credentials);
        $token = auth()->login($createUser);

        $this->setHeader(['Authorization'=>'Bearer '.$token]);
        return $this->message('注册成功！');

    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return $this->success(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}
